package edu.uoc.tdp.client.conexio;

import edu.uoc.tdp.beans.conexio.Usuari;
import edu.uoc.tdp.common.EOlympicsException;
import edu.uoc.tdp.common.EOlympicsExceptionConnexio;
import edu.uoc.tdp.common.RemotConexioInterface;
import edu.uoc.tdp.common.TDSLanguageUtils;
import java.rmi.RemoteException;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Grup TDP 1X4J
 */
public class PantallaCercaUsuaris extends javax.swing.JDialog {

    private RemotConexioInterface serveiRMIConnexio;
    private Usuari usuTriat;
    private boolean refrescar;

    public PantallaCercaUsuaris(java.awt.Frame parent, boolean modal,
            RemotConexioInterface serveiRMIConnexio) throws EOlympicsExceptionConnexio {
        super(parent, modal);

        TDSLanguageUtils.setDefaultLanguage("edu/uoc/tdp/i18n/messages");
        initComponents();

        usuTriat = null;
        this.serveiRMIConnexio = serveiRMIConnexio;

        this.setLocationRelativeTo(parent);

        setTitle(TDSLanguageUtils.getMessage("titol.general") + " - "
                + TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.titol"));

        jLabCognoms.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.txtCognoms"));
        jLabNom.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.txtNom"));
        jLabIdentificador.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.txtIdentif"));
        jBotoFiltrar.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.btnFiltrar"));
        jBotoAcceptar.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.btnAcceptar"));
        jBotoCancellar.setText(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.btnCancellar"));

        for (int i = 0; i < TaulaUsuaris.getColumnCount(); i++) {
            TaulaUsuaris.getColumnModel().getColumn(i).setHeaderValue(TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.taula.col" + i));
        }
        
        gestionaFiltre();

    }

    private void CarregaReixeta(String nom, String cognoms, String ident) {
        try {
            // Borrem la taula
            while (TaulaUsuaris.getRowCount() > 0) {
                ((DefaultTableModel) TaulaUsuaris.getModel()).removeRow(0);
            }

            List<Usuari> LlistaUsu = serveiRMIConnexio.getLlistaUsuaris(nom, cognoms, ident);

            // Omplim la taula amb la llista dels usuaris que no han estat borrats
            if (LlistaUsu.isEmpty()) {
                JOptionPane.showMessageDialog(null,
                        TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.missatge.nohihausu"),
                        TDSLanguageUtils.getMessage("connexio.pantalla.pantmiss.titol"), JOptionPane.INFORMATION_MESSAGE);
            } else {
                int fila = 0;
                for (Usuari usu : LlistaUsu) {
                    // Afegim una fila a la taula.
                    ((DefaultTableModel) TaulaUsuaris.getModel()).addRow(new Object[]{""});
                    // Carregar les dades a la fila corresponent de la taula
                    TaulaUsuaris.setValueAt(usu.getCognom1() + " " + usu.getCognom2(), fila, 0);
                    TaulaUsuaris.setValueAt(usu.getNom(), fila, 1);
                    TaulaUsuaris.setValueAt(usu.getIdUsuari(), fila, 2);
                    TaulaUsuaris.setValueAt(usu.getIdIntern(), fila, 3);
                    fila++;
                }
            }
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("ERR_REMOT_CERCAUSU"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsExceptionConnexio ex) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("ERR_CERCAUSU"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

        this.setRefrescar(false);
    }

    // S'encarrega de refrescar llista d'usuaris de la pantalla segons el filtre actiu
    private void gestionaFiltre() {
        if (jBotoFiltrar.isSelected()) {
            CarregaReixeta(jTextNom.getText(),
                    jTextCognoms.getText(),
                    jTextIdentificador.getText());
        } else {
            CarregaReixeta("", "", "");
        }
        jTextNom.setEnabled(!jBotoFiltrar.isSelected());
        jTextCognoms.setEnabled(!jBotoFiltrar.isSelected());
        jTextIdentificador.setEnabled(!jBotoFiltrar.isSelected());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TaulaUsuaris = new javax.swing.JTable();
        jBotoAcceptar = new javax.swing.JButton();
        jBotoCancellar = new javax.swing.JButton();
        jBotoFiltrar = new javax.swing.JToggleButton();
        jLabNom = new javax.swing.JLabel();
        jLabCognoms = new javax.swing.JLabel();
        jLabIdentificador = new javax.swing.JLabel();
        jTextCognoms = new javax.swing.JTextField();
        jTextNom = new javax.swing.JTextField();
        jTextIdentificador = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        TaulaUsuaris.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cognoms", "Nom", "Identificador", "Nº Ordre"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TaulaUsuaris.setNextFocusableComponent(jBotoAcceptar);
        jScrollPane1.setViewportView(TaulaUsuaris);
        TaulaUsuaris.getColumnModel().getColumn(0).setResizable(false);
        TaulaUsuaris.getColumnModel().getColumn(0).setPreferredWidth(200);
        TaulaUsuaris.getColumnModel().getColumn(1).setResizable(false);
        TaulaUsuaris.getColumnModel().getColumn(1).setPreferredWidth(100);
        TaulaUsuaris.getColumnModel().getColumn(2).setResizable(false);
        TaulaUsuaris.getColumnModel().getColumn(2).setPreferredWidth(70);
        TaulaUsuaris.getColumnModel().getColumn(3).setResizable(false);
        TaulaUsuaris.getColumnModel().getColumn(3).setPreferredWidth(70);

        jBotoAcceptar.setText("Acceptar");
        jBotoAcceptar.setNextFocusableComponent(jBotoCancellar);
        jBotoAcceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotoAcceptarActionPerformed(evt);
            }
        });

        jBotoCancellar.setText("Cancel·lar");
        jBotoCancellar.setNextFocusableComponent(jTextNom);
        jBotoCancellar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotoCancellarActionPerformed(evt);
            }
        });

        jBotoFiltrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/BotoFiltrar.png"))); // NOI18N
        jBotoFiltrar.setText("Filtrar");
        jBotoFiltrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jBotoFiltrar.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jBotoFiltrar.setNextFocusableComponent(TaulaUsuaris);
        jBotoFiltrar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jBotoFiltrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotoFiltrarActionPerformed(evt);
            }
        });

        jLabNom.setText("Nom");

        jLabCognoms.setText("Cognoms");

        jLabIdentificador.setText("Identificador Usuari");

        jTextCognoms.setNextFocusableComponent(jTextCognoms);

        jTextNom.setNextFocusableComponent(jTextIdentificador);

        jTextIdentificador.setNextFocusableComponent(jBotoFiltrar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabIdentificador)
                            .addComponent(jLabNom)
                            .addComponent(jLabCognoms))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextCognoms, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextIdentificador, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTextNom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)))
                        .addGap(18, 18, 18)
                        .addComponent(jBotoFiltrar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 440, Short.MAX_VALUE)
                        .addComponent(jBotoAcceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBotoCancellar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabCognoms)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabNom)
                        .addGap(15, 15, 15)
                        .addComponent(jLabIdentificador))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextCognoms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextIdentificador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jBotoFiltrar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBotoCancellar)
                    .addComponent(jBotoAcceptar))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(jBotoAcceptar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        setVisible(false);
    }//GEN-LAST:event_formWindowClosing

    private void jBotoAcceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotoAcceptarActionPerformed
        try {
            if (TaulaUsuaris.getSelectedRow() != -1) {
                usuTriat = serveiRMIConnexio.getUsuari(
                        Integer.parseInt(TaulaUsuaris.getValueAt(TaulaUsuaris.getSelectedRow(), 3).toString()));
                setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null,
                        TDSLanguageUtils.getMessage("connexio.pantalla.cercausu.missatge.selecusu"),
                        TDSLanguageUtils.getMessage("connexio.pantalla.pantmiss.titol"), JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("ERR_REMOT_ASSIGUSU"), "Error", JOptionPane.ERROR_MESSAGE);
        } catch (EOlympicsException ex) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("ERR_ASSIGUSU"), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jBotoAcceptarActionPerformed

    private void jBotoCancellarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotoCancellarActionPerformed
        usuTriat = null;
        setVisible(false);
    }//GEN-LAST:event_jBotoCancellarActionPerformed

    private void jBotoFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotoFiltrarActionPerformed
        gestionaFiltre();
    }//GEN-LAST:event_jBotoFiltrarActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        if (this.getRefrescar()) {
            gestionaFiltre();
        }
    }//GEN-LAST:event_formWindowActivated

    /**
     * Accessor de lectura de l'objecte usuari triat de la finestra de cerca.
     *
     * @return Objecte Usuari triat de la finestra de Cerca
     */
    public Usuari getUsuariTriat() {
        return usuTriat;
    }

    /**
     * Accessor de lectura de l'indicador de refresc de la finestra de cerca.
     *
     * @return indicador de refresc de la finestra de Cerca
     */
    public boolean getRefrescar() {
        return refrescar;
    }

    /**
     * Accessor d'escriptura de l'indicador de refresc de la finestra de cerca.
     *
     * @param refrescar indicador de refresc de la finestra de Cerca
     */
    public void setRefrescar(boolean refrescar) {
        this.refrescar = refrescar;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TaulaUsuaris;
    private javax.swing.JButton jBotoAcceptar;
    private javax.swing.JButton jBotoCancellar;
    private javax.swing.JToggleButton jBotoFiltrar;
    private javax.swing.JLabel jLabCognoms;
    private javax.swing.JLabel jLabIdentificador;
    private javax.swing.JLabel jLabNom;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextCognoms;
    private javax.swing.JTextField jTextIdentificador;
    private javax.swing.JTextField jTextNom;
    // End of variables declaration//GEN-END:variables
}
